#include "unixHeader.h"
#include <iostream>

#include <workflow/WFFacilities.h>
#include <wfrest/HttpServer.h>


using namespace std;
using namespace wfrest;

static WFFacilities::WaitGroup waitGroup(1);

void test0()
{
    HttpServer server;

    server.GET("/file/upload", [](const HttpReq * , HttpResp * resp){
        resp->File("./static/view/index.html");
    });

    server.GET("/file/upload/success", [](const HttpReq * , HttpResp * resp){
        resp->String("upload success");
    });

    server.POST("/file/upload", [](const HttpReq * req, HttpResp * resp){
        //resp->File("./static/view/index.html");
        if(req->content_type() == MULTIPART_FORM_DATA) {
            //获取文件的信息
            auto & formMap = req->form();
            string filename = formMap["file"].first;
            string content = formMap["file"].second;
            cout << "filename:" << filename << endl
                 << "content:" << content << endl;

            //将文件内容写入本地文件
            string filepath = "./tmp/" + filename;
            mkdir("./tmp", 0755);
            int fd = open(filepath.c_str(), O_CREAT|O_RDWR, 0755);
            if(fd < 0) {
                perror("open");
                return;
            }
            write(fd, content.c_str(), content.size());
            close(fd);

            //重定向
            resp->set_status_code("302");
            resp->headers["Location"] = "/file/upload/success";
        }
    });

    server.GET("/file/download", [](const HttpReq * req, HttpResp * resp){
        auto querylist = req->query_list();
        string filename = querylist["filename"];
        string filehash = querylist["filehash"];
        string filesize = querylist["filesize"];

        //下载文件(读取本地文件)
        string filepath = "./tmp/" + filename;
        int fd = open(filepath.c_str(), O_RDONLY);
        if(fd < 0) {
            perror("open");
            return;
        }
        //读取文件
        char buff[1024] = {0};
        int ret = read(fd, buff, sizeof(buff));
        close(fd);
        //设置响应
        resp->append_output_body(buff, ret);
        resp->headers["Content-Type"] = "application/octet-stream";
        resp->headers["Content-Disposition"] = "attachment;filename=" + filename;
    });

    if(server.track().start(8888) == 0) {
        server.list_routes();
        waitGroup.wait();
        server.stop();
    } else {
        printf("server cannnot start\n");
    }
}


int main()
{
    test0();
    return 0;
}

